<?php

/**
 * Created by JetBrains PhpStorm.
 * User: taoqili
 * Date: 12-7-18
 * Time: 上午11: 32
 * UEditor编辑器通用上传类
 */
class Uploader
{
    private $fileField; //文件域名
    private $file; //文件上传对象
    private $base64; //文件上传对象
    private $config; //配置信息
    private $oriName; //原始文件名
    private $fileName; //新文件名
    private $fullName; //完整文件名,即从当前配置目录开始的URL
    private $filePath; //完整文件名,即从当前配置目录开始的URL
    private $fileSize; //文件大小
    private $fileType; //文件类型
    private $stateInfo; //上传状态信息,
    private $stateMap = array( //上传状态映射表，国际化用户需考虑此处数据的国际化
        "SUCCESS", //上传成功标记，在UEditor中内不可改变，否则flash判断会出错
        "文件大小超出 upload_max_filesize 限制",
        "文件大小超出 MAX_FILE_SIZE 限制",
        "文件未被完整上传",
        "没有文件被上传",
        "上传文件为空",
        "ERROR_TMP_FILE" => "临时文件错误",
        "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
        "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
        "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
        "ERROR_CREATE_DIR" => "目录创建失败",
        "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
        "ERROR_FILE_MOVE" => "文件保存时出错",
        "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
        "ERROR_WRITE_CONTENT" => "写入文件内容错误",
        "ERROR_UNKNOWN" => "未知错误",
        "ERROR_DEAD_LINK" => "链接不可用",
        "ERROR_HTTP_LINK" => "链接不是http链接",
        "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确"
    );
	private $path;
	private $ext;
	private $width;
	private $height;
	private $_imgDo;

    /**
     * 构造函数
     * @param string $fileField 表单名称
     * @param array $config 配置项
     * @param bool $base64 是否解析base64编码，可省略。若开启，则$fileField代表的是base64编码的字符串表单名
     */
    public function __construct($fileField, $config, $type = "upload")
    {
		$this->_imgDo = false;
        $this->fileField = $fileField;
        $this->config = $config;
		$this->path = $this->config['path']?$this->config['path']:'';
        $this->type = $type;
		if($type == "oss"){
			$this->upOSS();
		}else if ($type == "remote") {
            $this->saveRemote();
        }else if($type == "thumb"){
			$this->width = $config['width'];
			$this->height = $config['height'];
			$this->thumb();
		} else if($type == "ossthumb"){
			$this->width = $config['width'];
			$this->height = $config['height'];
			$this->ossthumb();
		} else if($type == "upCert"){
			$this->width = $config['width'];
			$this->height = $config['height'];
			$this->upCert();
		}else if($type == "base64") {
            $this->upBase64();
        } else {
            $this->upFile();
        }

        $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
    }

    /**
     * 上传文件的主处理方法
     * @return mixed
     */
    private function upFile()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();		
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移动文件
        if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else { //移动成功
			$this->_imgDo = true;
            $this->stateInfo = $this->stateMap[0];
        }
    }

    /**
     * 处理base64编码的图片上传
     * @return mixed
     */
    private function upBase64()
    {
        $base64Data = $_POST[$this->fileField];
        $img = base64_decode($base64Data);

        $this->oriName = $this->config['oriName'];
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移动文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移动成功
            $this->stateInfo = $this->stateMap[0];
        }

    }

    /**
     * 拉取远程图片
     * @return mixed
     */
    private function saveRemote()
    {
        
		$imgUrl = htmlspecialchars($this->fileField);
        $imgUrl = str_replace("&amp;", "&", $imgUrl);
		//http开头验证
        if (strpos($imgUrl, "http") !== 0) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
            return;
        }
		$WAN = true;
		$fileType = $this->getFileExt();
		if (!in_array($fileType, $this->config['allowFiles'])){
			//获取请求头并检测死链
			//$heads = get_headers($imgUrl,1);
			$heads = DoCurl($imgUrl, array(), true);
			//if($_GET['mid']=='SPEGEKIGFN') var_dump($imgArr[1]);
			$WAN = false;
			if ($heads[0] != 200) {
				$this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");				
				return;
			}
			
			//格式验证(扩展名验证和Content-Type验证)
			$types = explode('/',$heads[1]);
			$fileType = $types[1];
			if($fileType == 'jpeg') $fileType = '.jpg';
			else  $fileType = '.'.$fileType;
			$this->ext = $fileType;
		}
		
        $this->fileType = $fileType;//$this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);
		if(is_file($this->filePath)){
			$this->stateInfo = $this->stateMap[0]; 
			return;
		}
		
		//获取请求头并检测死链
		//$heads = get_headers($imgUrl,1);
		if($WAN) $heads = DoCurl($imgUrl, array(), true);
		if ($heads[0] != 200) {
			$this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
			return;
		}
		
		
        if (!in_array($fileType, $this->config['allowFiles']) || !stristr($types[0], "image")) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
            return;
        }
		
		
        

        //打开输出缓冲区并获取远程图片
/*        $context = stream_context_create(
            array('http' => array(
                'follow_location' => false // don't follow redirects
            ))
        );
        readfile($imgUrl, false, $context);
        $img = ob_get_contents();*/
		//$img = DoCurl($imgUrl);
		$img = $heads[2];
        preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
		$this->oriName = $m ? $m[1]:"";
        $this->fileSize = strlen($img);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移动文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移动成功
			$this->_imgDo = true;
            $this->stateInfo = $this->stateMap[0];
        }

    }
	
	function thumb() {	//原始大图地址，缩略图宽度，高度，缩略图地址
		$real = false;
		if(empty($this->fileField)) return;
		$this->filePath = $src = APP_ROOT.$this->fileField;
		$this->height = $this->height?$this->height:0;
		
		/*if(!$this->ext){
			$this->ext = strtolower(strrchr($this->fileField, '.'));
			if(!$this->ext){
				if(!$imgage = @getimagesize($src)) return; //得到原始大图片
				switch ($imgage[2]) { // 图像类型判断
					case 1:
						$im = imagecreatefromgif($src);
						$this->ext = $this->fileType = '.gif';
						break;
					case 2:
						$im = imagecreatefromjpeg($src);
						$this->ext = $this->fileType = '.jpg';
						break;
					case 3:
						$im = imagecreatefrompng($src);
						$this->ext = $this->fileType = '.png';
						break;
				}
				$real = true;
			}
		}*/
		$this->fileName = $this->getFileName();
		$this->fullName = dirname($this->fileField).'/'.$this->width.'_'.$this->height.'/'.$this->fileName;
		$this->filePath = dirname($this->filePath).'/'.$this->width.'_'.$this->height.'/'.$this->fileName;
		
		if(is_file($this->filePath)){
			$this->stateInfo = $this->stateMap[0]; 
			return;
		}
		
		if(!$real){
			if(!$imgage = @getimagesize($src)) return; //得到原始大图片
			switch ($imgage[2]) { // 图像类型判断
				case 1:
					$im = imagecreatefromgif($src);
					$this->ext = $this->fileType = '.gif';
					break;
				case 2:
					$im = imagecreatefromjpeg($src);
					$this->ext = $this->fileType = '.jpg';
					break;
				case 3:
					$im = imagecreatefrompng($src);
					$this->ext = $this->fileType = '.png';
					break;
			}
		}
		$src_W = $imgage[0];
		$src_H = $imgage[1];
		$width =  $this->width;// = $imgage[0]; //获取大图片宽度
		$height = $this->height?$this->height:$width/($src_W/$src_H);// = $imgage[1]; //获取大图片高度		
		
        //$this->fullName = $this->getFullName();
        //$this->filePath = $this->getFilePath();
        //$this->fileName = $this->getFileName();
		
        $dirname = dirname($this->filePath);
		
		 //创建目录失败
        if (!dmkdir($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }
		
		$ratio_orig = $src_W/$src_H;

		if ($width/$height > $ratio_orig) {
		   $width = $height*$ratio_orig;
		} else {
		   $height = $width/$ratio_orig;
		}
		
		/*if($crop){
			if($w < $width or $h < $height) return "Picture is too small!";
			$ratio = max($width/$w, $height/$h);
			$h = $height / $ratio;
			$x = ($w - $width / $ratio) / 2;
			$w = $width / $ratio;
		  }else{
			if($w < $width and $h < $height) return "Picture is too small!";
			$ratio = min($width/$w, $height/$h);
			$width = $w * $ratio;
			$height = $h * $ratio;
			$x = 0;
		 }*/		
		
		$tn = imagecreatetruecolor($width, $height); //创建缩略图
		imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); //复制图像并改变大小
		imagejpeg($tn, $this->filePath, 100); //输出图像
		$this->stateInfo = $this->stateMap[0];
	}
	/*
	*
	*	生成缩略图到OSS
	*
	*
	*
	*/
	private function ossthumb(){
		//$http = strpos($this->fileField,'http');
		//替换oss域名
		//替换cdn域名
		if(empty($this->fileField)) return;
		$url = str_replace(array('http://public.sichem.cn/','http://uposs.3668.sichem.cn/'),array('',''),$this->fileField);
		
		//路径配置
		$bucket = 'sichemfile';
		$object = $url;
		
		$this->filePath = $src = $localurl = APP_ROOT.'/upload/OSSTMP/'.$url;
		$this->height = $this->height?$this->height:0;		
		
		$this->fileName = $this->getFileName();
		//$this->fullName = dirname($this->fileField).'/'.$this->width.'_'.$this->height.'/'.$this->fileName;  //返回用
		$this->filePath = dirname($this->filePath).'/'.$this->width.'_'.$this->height.'/'.$this->fileName;	//实际保存用
		$this->fullName = $OSSfile = dirname($url).'/'.$this->width.'_'.$this->height.'/'.$this->fileName;	//OSS路径用
		
		//载入OSS SDK
		if(!defined('OSSSDK'))	{
			include libfile('oss/sdk','class');
			define('OSSSDK',TRUE);
		}
		$oss_sdk_service = new ALIOSS();
		$oss_sdk_service->set_debug_mode(false);

		//判断内存中是否记录已经生成过。提高运行速度
		$r = memory('get' , 'thumb-'.md5($OSSfile));
		if($r){
			$this->stateInfo = $this->stateMap[0];
			return;
		}
		
		//判断远程OSS服务器是否存在
		$response = $oss_sdk_service->is_object_exist($bucket,$OSSfile);
		if($response->isOk()){
			$this->stateInfo = $this->stateMap[0];
			memory('set' , 'thumb-'.md5($OSSfile),$this->fullName);
			return;
		}
		
		if(strpos($url,'http') === 0){
			//远程下载图片进行缩略图处理
			return;
		}else{			
			//使用OSS内部域名下载
			//oss-cn-hangzhou-internal.aliyuncs.com
			//;
			if(!is_file($localurl) && dmkdir(dirname($localurl))){ //本地不存在
				$options = array(
				ALIOSS::OSS_FILE_DOWNLOAD => $localurl,
					//ALIOSS::OSS_CONTENT_TYPE => 'txt/html',
				);	
				$response = $oss_sdk_service->get_object($bucket,$object,$options);
				if(!$response->isOk()){
					return;
				}				
			}
		}
		if(!$imgage = @getimagesize($localurl)) return; //得到原始大图片
		// 打开图片
		switch ($imgage[2]) { // 图像类型判断
			case 1:
				$im = imagecreatefromgif($localurl);
				$this->ext = $this->fileType = '.gif';
				break;
			case 2:
				$im = imagecreatefromjpeg($localurl);
				$this->ext = $this->fileType = '.jpg';
				break;
			case 3:
				$im = imagecreatefrompng($localurl);
				$this->ext = $this->fileType = '.png';
				break;
		}
			
			
		$src_W = $imgage[0];
		$src_H = $imgage[1];
		$width =  $this->width;// = $imgage[0]; //获取大图片宽度
		$height = $this->height?$this->height:$width/($src_W/$src_H);// = $imgage[1]; //获取大图片高度		
		
		$dirname = dirname($this->filePath);
		//创建目录失败
		if (!dmkdir($dirname)) {
			$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
			return;
		} else if (!is_writeable($dirname)) {
			$this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
			return;
		}
			
		$ratio_orig = $src_W/$src_H;
		if ($width/$height > $ratio_orig) {
		   $width = $height*$ratio_orig;
		} else {
		   $height = $width/$ratio_orig;
		}
			
		//保存缩略图
		$tn = imagecreatetruecolor($width, $height); //创建缩略图
		imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); //复制图像并改变大小
		imagejpeg($tn, $this->filePath, 100); //输出图像
			
		//读取缩略图			
		$fp = fopen($this->filePath,'r'); 
		if($fp){ 
			$f = fstat($fp); 
			$length = $f['size'];
			while(!feof($fp)){ 
				$content .= fgets($fp,8192); 
			} 
		} 
		//上传到OSS
		$upload_file_options = array(
			'content' => $content,
			'length' => $length,
			ALIOSS::OSS_HEADERS => array(
				'Expires' => '2012-10-01 08:00:00',
			),
		);
			
		$response = $oss_sdk_service->upload_file_by_content($bucket,$OSSfile ,$upload_file_options);	
		if($response->isOk()){
			$this->stateInfo = $this->stateMap[0];
			memory('set' , 'thumb-'.md5($OSSfile),$this->fullName);
		}else{
			$this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
		}		
	}	
	/*
    *	上传到ALIYUN OSS
    *	@return mixed
    */
    private function upOSS()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();		
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

		session_write_close();
		set_time_limit(0); 
        if(!defined('OSSSDK'))	{
			include libfile('oss/sdk','class');
			define('OSSSDK',TRUE);
		}
		
		$oss_sdk_service = new ALIOSS();

		//设置是否打开curl调试模式
		$oss_sdk_service->set_debug_mode(FALSE);
		
		$bucket = 'sichemfile';
		
		$fp = fopen($file["tmp_name"],'r'); 
        if($fp){ 
            $f = fstat($fp); 
            $length = $f['size'];
            while(!feof($fp)){ 
                $content .= fgets($fp,8192); 
            } 
        } 
		//echo $content;
		$upload_file_options = array(
			'content' => $content,
			'length' => $length,
			ALIOSS::OSS_HEADERS => array(
				'Expires' => '2012-10-01 08:00:00',
			),
		);
		
		$response = $oss_sdk_service->upload_file_by_content($bucket,$this->fullName ,$upload_file_options);	
		if($response->isOk()){
			$this->stateInfo = $this->stateMap[0];
		}else{
			$this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
		}


        //移动文件
        //if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
        //    $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        //} else { //移动成功
		//	$this->_imgDo = true;
        //    $this->stateInfo = $this->stateMap[0];
        //}
    }
	
	
	
	
	 /**
     * 上传证书
     * @return mixed
     */
    private function upCert()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();		
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }
		
		session_write_close();
		set_time_limit(0); 
        if(!defined('OSSSDK'))	{
			include libfile('oss/sdk','class');
			define('OSSSDK',TRUE);
		}
		
		$oss_sdk_service = new ALIOSS();

		//设置是否打开curl调试模式
		$oss_sdk_service->set_debug_mode(FALSE);
		
		$bucket = 'sichem-wx-sert';
		
		$fp = fopen($file["tmp_name"],'r'); 
        if($fp){ 
            $f = fstat($fp); 
            $length = $f['size'];
            while(!feof($fp)){ 
                $content .= fgets($fp,8192); 
            } 
        } 
		//echo $content;
		$upload_file_options = array(
			'content' => $content,
			'length' => $length,
			ALIOSS::OSS_HEADERS => array(
				'Expires' => '2012-10-01 08:00:00',
			),
		);
		//var_dump($file["tmp_name"]);
		
		$response = $oss_sdk_service->upload_file_by_content($bucket,strrchr($this->fullName,'cert/') ,$upload_file_options);	
		//var_dump($response);
        //移动文件
        if ((!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) || !$response->isOk()) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else { //移动成功
			$this->_imgDo = true;
            $this->stateInfo = $this->stateMap[0];
        }
    }
	
    /**
     * 上传错误检查
     * @param $errCode
     * @return string
     */
    private function getStateInfo($errCode)
    {
        return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
    }

    /**
     * 获取文件扩展名
     * @return string
     */
    private function getFileExt()
    {
        if(!$this->ext){
			$this->ext = strtolower(strrchr($this->oriName, '.'));
			if(!$this->ext){
				if(!$imgage = @getimagesize($this->file['tmp_name'])) return; //得到原始大图片
				switch ($imgage[2]) { // 图像类型判断
					case 1:
						$this->ext = $this->fileType = '.gif';
						break;
					case 2:
						$this->ext = $this->fileType = '.jpg';
						break;
					case 3:
						$this->ext = $this->fileType = '.png';
						break;
				}
			}
		}
		return $this->ext;
    }

    /**
     * 重命名文件
     * @return string
     */
    private function getFullName()
    {
        global $_G;
		//替换日期事件
        $t = time();
        $d = explode('-', date("Y-y-m-d-H-i-s"));
        $format = $this->path?$this->path:$this->config["pathFormat"];
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);
		$format = str_replace("{_uid}", $_G['_uid']?$_G['_uid']:$_G['g_uid'], $format);
		$format = str_replace("{mid}/", $_G['g_mid']?$_G['g_mid'].'/':'', $format);
		$format = str_replace("{zid}/", $_SESSION['zid']?$_SESSION['zid'].'/':'', $format);
		$format = str_replace("{type}/", $_G['up_type']?$_G['up_type'].'/':'', $format);

        //过滤文件名的非法自负,并替换文件名
        $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
        $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
        $format = str_replace("{filename}", $oriName, $format);

        //替换随机字符串
        $randNum = rand(1, 10000000000) . rand(1, 10000000000);
        if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
            $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
        }

        $ext = $this->getFileExt();
		if($this->width && $this->height) $v = '_'.$this->width.'_'.$this->height;
		else $v = '';
        return $format . $v . $ext;
    }

    /**
     * 获取文件名
     * @return string
     */
    private function getFileName () {
        return substr($this->filePath, strrpos($this->filePath, '/') + 1);
    }

    /**
     * 获取文件完整路径
     * @return string
     */
    private function getFilePath()
    {
        $fullname = $this->fullName;
        $rootPath = $_SERVER['DOCUMENT_ROOT'];
        if (substr($fullname, 0, 1) != '/') {
            $fullname = '/' . $fullname;
        }

        return $rootPath . $fullname;
    }
	
	private function pictype ( $file ) 
	{ 
		 /*$png_header = "/x89/x50/x4e/x47/x0d/x0a/x1a/x0a"; 
		 $jpg_header = "/xff/xd8";*/ 
	
		 $header = file_get_contents ( $file , 0 , NULL , 0 , 5 ); 
	
		 //echo bin2hex($header); 
		 if ( $header { 0 }. $header { 1 }== "/x89/x50" ) 
		 { 
			 return 'png' ; 
		 } 
		 else if( $header { 0 }. $header { 1 } == "/xff/xd8" ) 
		 { 
			 return 'jpeg' ; 
		 } 
		 else if( $header { 0 }. $header { 1 }. $header { 2 } == "/x47/x49/x46" ) 
		 { 
			 
			 if( $header { 4 } == "/x37" ) 
				 return 'gif87' ; 
			 else if( $header { 4 } == "/x39" ) 
				 return 'gif89' ; 
		 } 
		 
	} 
    /**
     * 文件类型检测
     * @return bool
     */
    private function checkType()
    {
        return in_array($this->getFileExt(), $this->config["allowFiles"]);
    }

    /**
     * 文件大小检测
     * @return bool
     */
    private function  checkSize()
    {
        return $this->fileSize <= ($this->config["maxSize"]);
    }

    /**
     * 获取当前上传成功文件的各项信息
     * @return array
     */
    public function getFileInfo()   {	
		/*
		源OSS域名 http://public.sichem.cn/
		uposs.3668.sichem.cn   CDN加速域名回源地址 http://public.sichem.cn/
		*/
		if(in_array($this->type, array("oss","ossthumb")))
			$url = 'http://uposs.3668.sichem.cn/'.$this->fullName;
		else	$url = $this->fullName;
		
        $a = array(
            "state" => $this->stateInfo,  //错误标示
            "url" => $url, //上传后的完整路径
            "title" => $this->fileName, 	//新文件名
            "original" => $this->oriName, //原始名称
            "type" => $this->fileType, 	//文件类型
            "size" => $this->fileSize //文件尺寸
        );
		if($this->stateInfo =='SUCCESS' && in_array($this->type,array('remote','upload')) && $this->_imgDo){			
			$id = C::t('upload')->insert($a);
			$a['id'] = $id;
		}
		return $a;
    }
	
}